<template>
  <div>
    <fieldset>
      <legend>按钮鉴权</legend>
      <div class="content" v-if="isLogin">
        <ul>
          <li v-for="(item, index) of arr" :key="index">
            <b>{{ item }}</b>
            <button v-has:[btnAuthority]="'add'">增加</button>
            <button v-has:[btnAuthority]="'edit'">编辑</button>
            <button v-has:[btnAuthority]="'delete'">删除</button>
            <button v-has:[btnAuthority]="'read'">查看</button>
          </li>
        </ul>
      </div>
      <div class="login-container" v-else>
        <h1>请登入</h1>
        用户名:
        <input type="text" v-model="username" />
        <br />
        密码:
        <input type="password" v-model="password" @keydown.enter="login" />
        <br />
        <button @click="login">点击登入</button>
      </div>
    </fieldset>
  </div>
</template>
<script>
export default {
  data() {
    return {
      isLogin: false,
      username: "",
      password: "",
      btnAuthority: [],
      arr: ["今天", "明天", "后天", "如果"],
    };
  },
  directives: {
    has: {
      inserted(el, binding) {
        let roleAuthority = binding.arg;
        let requireAuthority = binding.value;
        let hasAuthority = roleAuthority.includes(requireAuthority);
        if (!hasAuthority) {
          el.parentNode.removeChild(el);
        }
      },
    },
  },
  methods: {
    async login() {
      let info = {
        username: this.username,
        password: this.password,
      };
      let result = await fetch("http://chst.vip/users/login", {
        method: "post",
        body: JSON.stringify(info),
        headers: {
          "content-type": "application/json",
        },
      }).then((body) => body.json());
      console.log(result);
      this.btnAuthority = result.permission.buttons;
      if (result.state) {
        this.isLogin = true;
      }
    },
  },
};
</script>
<style scoped>
</style>